package com.smasher.print.dw;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.util.Log;

import java.util.List;

import dw.printer.Printer;
import dw.printer.UsbHelper;

public class ConnectUSB implements ConnectDW {

    public static final String TAG = "ConnectUSB";

    private Printer printer;

    private List<UsbDevice> deviceList;

    private boolean isConnect;

    private boolean useAuto = true;

    public ConnectUSB(Context context, Printer printer) {
        this.printer = printer;
    }

    @Override
    public void start(Context context) {
        deviceList = printer.getUsbDeviceList();
    }

    @Override
    public void stop(Context context) {

    }

    @Override
    public void connPrint(Context context) {
        if (useAuto) {
            printer.openUsbAuto(new UsbHelper.UsbMsgCallback() {

                @Override
                public void onUsbConnectSuccess() {
                    isConnect = true;
                }

                @Override
                public void onUsbDisconnect() {
                    isConnect = false;
                }

                @Override
                public void onUsbOpenFailed() {

                }
            });
        } else {
            UsbDevice usbDevice = findUsbDevice();
            if (usbDevice != null) {
                actualConnect(usbDevice);
            }
        }

    }


    @Override
    public void disConnPrint(Context context) {
        printer.closeUsb();
    }

    @Override
    public boolean isUnConnect(Context context) {
        return !isConnect;
    }

    private void actualConnect(UsbDevice usbDevice) {
        printer.openUsb(usbDevice, new UsbHelper.UsbMsgCallback() {
            @Override
            public void onUsbConnectSuccess() {
                Log.i(TAG, "onUsbConnectSuccess: " + "   VID:" + usbDevice.getVendorId() + "     PID:" + usbDevice.getProductId());
//                binding.setDeviceName("VID:" + usbDevice.getVendorId() + "     PID:" + usbDevice.getProductId());
//                binding.setConnectState("已连接");
                isConnect = true;
            }

            @Override
            public void onUsbDisconnect() {
//                binding.setConnectState("已断开");
                Log.i(TAG, "onUsbDisconnect: ");
                isConnect = false;
            }

            @Override
            public void onUsbOpenFailed() {
                Log.i(TAG, "onUsbOpenFailed: ");
            }
        });
    }


    private UsbDevice findUsbDevice() {
        for (UsbDevice device : deviceList) {
            // 匹配 vendorId 和 productId
            if (device.getVendorId() == 7554 && device.getProductId() == 22304) {
                return device; // 找到匹配设备
            }
        }
        return null;
    }
}
